//
//  AddressViewController.m
//  Address
//
//  Created by 胡岩 on 16/2/24.
//  Copyright © 2016年 MagicalYan. All rights reserved.
//

#import "AddressViewController.h"
#import "CityModel.h"
#import "AddressView.h"

@interface AddressViewController ()<UITableViewDelegate, UITableViewDataSource, AddressViewDelegate>

@property (nonatomic, strong) NSMutableDictionary *cityDic;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *names;

@property (nonatomic, strong) AddressView *addressView;

@end

@implementation AddressViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    NSArray *array = [_cityDic  objectForKey:[NSString stringWithFormat:@"%@", _names[indexPath.section]]];
    CityModel *model = array[indexPath.row];
    cell.textLabel.text = model.cityname;
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _names.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *array = [_cityDic objectForKey:[NSString stringWithFormat:@"%@", _names[section]]];
    return array.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 20, 30)];
    label.backgroundColor = [UIColor grayColor];
    label.text = [NSString stringWithFormat:@"   %@", _names[section]];
    return label;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}


- (NSString *)firstCharactor:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _cityDic = [NSMutableDictionary dictionary];
        _names = [NSMutableArray array];
        NSString *pathCity = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"json"];
        NSString *strCity = [NSString stringWithContentsOfFile:pathCity encoding:NSUTF8StringEncoding error:nil];
        NSData *dataCity = [strCity dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dicCity = [NSJSONSerialization JSONObjectWithData:dataCity options:NSJSONReadingMutableContainers error:nil];
        for (NSDictionary *dic in [dicCity objectForKey:@"RECORDS"]) {
            CityModel *model = [[CityModel alloc] initWithDictionary:dic];
            NSString *str = [model.cityname substringToIndex:1];
            if ([str isEqualToString:@"市"] || [str isEqualToString:@"县"]) {
                continue;
            }
            NSString *pinyin = [self firstCharactor:str];
            if ([_cityDic objectForKey:pinyin]) {
                if ([str isEqualToString:@"长"]) {
                    NSMutableArray *array = [_cityDic objectForKey:@"C"];
                    [array addObject:model];
                } else {
                    NSMutableArray *array = [_cityDic objectForKey:pinyin];
                    [array addObject:model];
                }
            } else {
                NSMutableArray *array = [NSMutableArray array];
                [array addObject:model];
                if ([str isEqualToString:@"长"]) {
                    [_cityDic setObject:array forKey:@"C"];
                } else {
                    [_cityDic setObject:array forKey:pinyin];
                    if (_names.count == 0) {
                        [_names addObject:pinyin];
                    } else if (_names.count == 1) {
                        if ([pinyin compare:_names.firstObject] == -1) {
                            [_names addObject:pinyin];
                        } else if ([pinyin compare:_names.firstObject] == 1) {
                            [_names insertObject:pinyin atIndex:0];
                        }
                    } else {
                        if ([_names.firstObject compare:pinyin] == 1) {
                            [_names insertObject:pinyin atIndex:0];
                        } else if ([_names.lastObject compare:pinyin] == -1) {
                            [_names addObject:pinyin];
                        } else {
                            for (int i = 0; i < _names.count - 1; i++) {
                                if ([_names[i] compare:pinyin] == -1 && [pinyin compare: _names[i + 1]] == -1) {
                                    [_names insertObject:pinyin atIndex:i + 1];
                                    break;
                                }
                            }
                        }
                        
                    }
                }
            }
        }
        _addressView = [[AddressView alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 25, 0, 25, self.view.frame.size.height) names:_names];
        [self.view addSubview:_addressView];
        _addressView.delegate = self;
    }
    return self;
}

- (void)addressView:(AddressView *)addressView didSelectNum:(NSInteger)number {
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:number] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
